package com.bdhub.handld;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bdhub.im.server.protobuf.MessageProtobuf.CMsg;
import com.bdhub.im.server.protobuf.MessageProtobuf.CMsgHead;

import java.util.Map;
import java.util.UUID;

/***
 * 消息处理器,对接收的消息进行处理
 * 
 * @author lp
 * 
 */
public class MsgProcesser {
	private int second = 20;
	private int allowFree = 2;
	private int bsecond = 20;
	private int ballowFree = 2;
	private ClientBootstrap clientBootstrap = null;
	// private ExecutorServiceFactory poolFactory;
	// private static MessageTimeOutManager messageTimeOutManager =
	// MessageTimeOutManager
	// .getInstance();
	private HeartThread heartThread;

	public void setLastReadTime(long lastReadTime) {
		if (heartThread != null) {
			heartThread.setLastReadTime(lastReadTime);
		}
	}

	public MsgProcesser(ClientBootstrap clientBootstrap) {
		this.clientBootstrap = clientBootstrap;
	}

	public void processMsg(CMsg msg) {
		int int_type = msg.getHead().getType();
		switch (int_type) {
		case 3001: // 握手回应
			Map<String, Object> m = JSON.parseObject(msg.getHead()
					.getComments(), new TypeReference<Map<String, Object>>() {
			});
			int _type = Integer.parseInt(m.get("type").toString());
			switch (_type) {
			case 1001:
				if (Integer.parseInt(m.get("status").toString()) == 200) {
					try {
						allowFree = Integer.parseInt(m.get("allowFree")
								.toString());
						second = Integer
								.parseInt(m.get("heartBeat").toString());

						ballowFree = Integer.parseInt(m.get("bkAllowFree")
								.toString());
						bsecond = Integer.parseInt(m.get("bkHeartBeat")
								.toString());
					} catch (Exception e) {
						e.printStackTrace();
					}
					try {
						// 通知消息超时管理，连接被重置
						clientBootstrap.getMessageTimeOutManager()
								.connectReset();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					// 启动心跳
					// HeartThread thread = new HeartThread(second,
					// bsecond,allowFree,ballowFree);
					// ReStartEventListener.getInstance().addListener(thread);
					// Thread t2 = new Thread(thread);
					// t2.start();
					//
					heartThread = new HeartThread(clientBootstrap,second, bsecond, allowFree,ballowFree);
					clientBootstrap.getPoolFactory().initWorkPool(1);
					clientBootstrap.getPoolFactory().executeWorker(heartThread);
				}
				break;
			}

			break;
		}
	}

	// private Message.Builder buildMsg(MessageProto.Message resp)
	// {
	// UUID uuid = UUID.randomUUID();
	//
	// // //build message
	// Map<String, Object> map = null;
	// if(!resp.getHead().getComments().equals(""))
	// {
	// map = JSON.parseObject(resp.getHead().getComments(), new
	// TypeReference<Map<String, Object>>(){});
	// }
	//
	// if ( map == null )
	// {
	// map = new HashMap<String, Object>();
	// }
	//
	// map.put("type", resp.getHead().getType());
	// map.put("mid", resp.getHead().getMid());
	//
	// String strjson = JSON.toJSONString(map);
	// Head.Builder head = Head.newBuilder();
	// head.setType(3002);
	// head.setMid(uuid.toString());
	// head.setComments(strjson);
	//
	// Message.Builder msg = Message.newBuilder();
	// msg.setHead(head);
	// //
	//
	// return msg;
	// }

	private static class HeartThread implements Runnable {
		private CMsg.Builder msg = null;
		private int second = 10;
		private int bsecond = 10;
		private UUID uuid = null;
		private long sleepTime = 0;
		private int changed = 100;
		private int allowFree, ballowFree;
		private long lastReadTime;
		private ClientBootstrap clientBootstrap;

		public HeartThread(ClientBootstrap clientBootstrap, int s, int bs,
				int allowFree, int ballowFree) {
			this.clientBootstrap = clientBootstrap;
			second = s;
			bsecond = bs;
			this.allowFree = allowFree;
			this.ballowFree = ballowFree;
			addOutTimeHandler();
		}

		/**
		 * 添加超时时间控制handler
		 */
		private void addOutTimeHandler() {
			if (this.clientBootstrap.getAppStatus() == 0) {// 前台
				clientBootstrap.addTimeOutHandler(allowFree);
			} else {// 后台
				clientBootstrap.addTimeOutHandler(ballowFree);
			}
		}

		public void run() {
			try {
				// send message
				// 如果，连接重连或关闭，结束心跳信号的发送。结束该线程
				while (true) {
					changed = clientBootstrap.getAppStatus();

					uuid = UUID.randomUUID();
					// build message
					CMsgHead.Builder head = CMsgHead.newBuilder();
					head.setType(1000);
					head.setMid(uuid.toString());
					head.setFromId(clientBootstrap.getFmid());
					msg = CMsg.newBuilder();
					msg.setHead(head);
					clientBootstrap.addMsg(msg.build());
					lastReadTime = System.currentTimeMillis();
					try {
						if (clientBootstrap.getAppStatus() == 0) {// 前台
							sleepTime = second * 1000;
							// Thread.sleep(second * 1000);
						} else {// 后台
							sleepTime = bsecond * 1000;
							// Thread.sleep(bsecond * 1000);
						}
						long tmp = 0;
						while ((tmp <= sleepTime)) {
							if (changed != clientBootstrap.getAppStatus()) {
								addOutTimeHandler();
								break;
							}
							Thread.sleep(1000);
							tmp = System.currentTimeMillis() - lastReadTime;
						}

					} catch (InterruptedException e) {
						throw e;
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		public void setLastReadTime(long lastReadTime) {
			this.lastReadTime = lastReadTime;
		}

	}

}
